import java.io.FileInputStream;
import java.io.IOException;
import java.sql.*;
import java.util.Properties;

public class InsertImageForUser {

    public static void main(String[] args) {
        
        // 设置表格及列信息
        String databaseName = "message"; // 数据库名
        String tableName = "user"; // 数据库表名
        String targetColumn = "username"; // 用来查找的列名
        String imageColumn = "image";
        String targetValue = "SJJ"; // 用来查找的目标值
        String imageFilePath = "/home/Shujunjie/Images/ImageForSJJ.jpg"; // 要插入的图片路径

        // 设置数据库连接信息
        String dbUrl = "jdbc:mysql://localhost:3306/"+databaseName+"?useSSL=false&serverTimezone=UTC";
        String dbUsername = "root"; // 数据库用户名
        String dbPassword = "your_password_for_mysql"; // 数据库密码

        // MySQL 插入图片
        try (Connection conn = DriverManager.getConnection(dbUrl, dbUsername, dbPassword)) {
            // SQL 语句
            String sql = "UPDATE " + tableName + " SET " + imageColumn + " = ? WHERE " + targetColumn + " = ?";

            // 通过PreparedStatement执行插入操作
            try (PreparedStatement stmt = conn.prepareStatement(sql)) {
                // 读取图片文件
                FileInputStream inputStream = new FileInputStream(imageFilePath);
                stmt.setBinaryStream(1, inputStream); // 设置图片数据流
                stmt.setString(2, targetValue); // 设置目标值

                // 执行更新操作
                int rowsAffected = stmt.executeUpdate();
                System.out.println("Rows affected: " + rowsAffected);
            } catch (IOException e) {
                System.err.println("Error reading image file: " + e.getMessage());
            }
        } catch (SQLException e) {
            System.err.println("Database connection error: " + e.getMessage());
        }
    }
}
